<!--
 * @Author: sky 11864026+jfcode81@user.noreply.gitee.com
 * @Date: 2025-09-10 15:00:58
 * @LastEditors: sky 11864026+jfcode81@user.noreply.gitee.com
 * @LastEditTime: 2025-09-11 16:47:02
 * @FilePath: \trading-center-pc\pages\market\home.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { productListApi, productListBeforeApi } from '~/server/goodsApi'
import { reactive, ref, watch, computed } from 'vue'
import { ProductListQuery, ProductsInfo } from '~/types/goods'
import { seckillTimeApi } from '~/server/activityApi'

// 定义搜索结果选中参数类型
interface SearchCheckedParams {
  productCategory?: number[]
  productBrand?: number[]
  productTagList?: number
}

const route = useRoute()
const searchValue = ref<string>(String(route.query.searchValue || '')) //搜索框输入词
const productCid = ref<string>(String(route.query.productCid || '')) //商品分类id，三级分类id

//窗口的高度
const { getWindowHeight } = useScrollHeight()
const ScrollHeight = ref<number>((getWindowHeight() || 800) - 176 - 140)

watch(
  () => route.query.searchValue,
  (newValue) => {
    const searchVal = String(newValue || '')
    searchValue.value = searchVal
    where.keyword = searchVal
    where.cid = ''
    where.brandId = ''
    where.tagId = null
    seachLists[0].list = []
    seachLists[1].list = []
    seachLists[2].list = []
    getSeachList()
    getList()
  },
)
watch(
  () => route.query.productCid,
  (newValue) => {
    if (newValue) {
      where.cid = String(newValue)
      getList()
    }
  },
)
/**
 * 列表
 */
// 热销商品数据 - 独立维护，不受搜索影响
const hotProductsWhere = reactive<ProductListQuery>({
  page: 1,
  limit: 10,
  brandId: '',
  cid: '',
  keyword: '',
  maxPrice: null,
  merId: '',
  minPrice: null,
  priceOrder: '',
  salesOrder: 'desc', // 按销量降序排列
  tagId: null,
})

const { data: hotProductsData, refresh: getHotProducts } = await useAsyncData(
  'hotProducts',
  async () => productListApi(hotProductsWhere),
  {
    default: () => ({
      list: [],
      total: 0,
    }),
  },
)

// 计算热销商品列表（按销量排序，取前3个）
const hotProductsList = computed(() => {
  if (!hotProductsData.value?.list?.length) return []
  return hotProductsData.value.list
    .filter((item: any) => item.sales > 0) // 过滤有销量的商品
    .sort((a: any, b: any) => (b.sales || 0) - (a.sales || 0)) // 按销量降序排序
    .slice(0, 3) // 取前3个
})

// 主列表数据 - 受搜索和筛选影响
const where = reactive<ProductListQuery>({
  page: 1,
  limit: 10,
  brandId: '',
  cid: productCid.value,
  keyword: searchValue.value,
  maxPrice: null,
  merId: '',
  minPrice: null,
  priceOrder: '',
  salesOrder: '',
  tagId: null,
})
const {
  data: tableData,
  refresh: getList,
  pending: listLoading,
} = await useAsyncData(async () => productListApi(where), {
  default: () => ({
    list: [],
    total: 0,
  }),
})

console.log(tableData.value)

// 分页数据
const pageChange = (e: number) => {
  where.page = e
  getList()
}
const hotSize = ref({
  width: '200px',
  height: '200px',
})

const proSize = ref({
  width: '226px',
  height: '226px',
})

const seachLists = reactive([
  {
    name: '商品品牌',
    list: [],
    checked: [],
    type: 'productBrand',
    multiple: true, //是否是多选
    showMore: true, //true显示展开
    isShowBtnMore: false,
  },
  {
    name: '商品分类',
    list: [],
    checked: [],
    type: 'productCategory',
    multiple: true,
    showMore: true, //true显示展开
    isShowBtnMore: false,
  },
  {
    name: '商品标签',
    list: [],
    checked: [],
    type: 'productTagList',
    multiple: false,
    showMore: true, //true显示展开
    isShowBtnMore: false,
  },
])

//搜索品牌、分类 筛选数据/
const { refresh: getSeachList } = await useAsyncData(async () => {
  let data = await productListBeforeApi({ keyword: searchValue.value })
  seachLists[0].list = data?.brandList
  seachLists[1].list = data?.categoryList
  seachLists[2].list = data?.productTagList
})

const getProductListBefore = async () => {
  let data = await productListBeforeApi({ keyword: searchValue.value })
  seachLists[0].list = data?.brandList
  seachLists[1].list = data?.categoryList
  seachLists[2].list = data?.productTagList
}
getProductListBefore()

// 初始化时获取热销商品数据
getHotProducts()

//获取搜索选中结果
const handleSubmitChecked = (list: SearchCheckedParams) => {
  where.cid = list.productCategory ? list.productCategory.join(',') : ''
  where.brandId = list.productBrand ? list.productBrand.join(',') : ''
  where.tagId = list.productTagList || null
  getList()
}

//综合排序筛选回调
const handleSubmitSelect = (e: ProductListQuery) => {
  Object.assign(where, e)
  getList()
}
</script>

<template>
    <div class="seckill_list pt-60px">
        <div class="wrapper_1200">
            <div class="fontColor333 text-50px text-center font-700 alimama">昌欣超市</div>
            <div class="sologan text-center mb-50px mt-20px">品质保证，源头直采，让您买得放心。</div>
            <div class="contentBox flex">
                <div class="hot">
                    <div class="listStyle">
                        <div class="title text-center alimama"><i class="iconfont icon-hot"></i>热销商品</div>
                        <div v-if="hotProductsList.length > 0">
                            <product-seach :list="hotProductsList" :isHot="true" :size-data="hotSize" />
                        </div>
                        <div v-else class="w-100%">
                            <empty-page title="暂无热销商品哟~">
                                <template #emptyImage>
                                    <img src="@/assets/images/wushangpin.png" style="width: 100%;" />
                                </template>
                            </empty-page>
                        </div>
                    </div>

                </div>
                <div class="rightBox">
                    <div class="product_list h-100%">
                        <div class="h-100%">
                            <div class="b-rd-16px bg-#FFFFFF mb-20px">
                                <seach-list :list="seachLists" v-if="
            (seachLists[0].list && seachLists[0].list.length > 0) ||
            (seachLists[1].list && seachLists[1].list.length > 0) ||
            (seachLists[2].list && seachLists[2].list.length > 0)
          " @handle-submit-checked="handleSubmitChecked" />
                            </div>
                            <div class="acea-row sort items-center w-100% h-60px bg-#FFFFFF b-rd-12px pl-20px pr-20px">
                                <sort-seach :where="where" @handle-submit-select="handleSubmitSelect" />
                            </div>
                            <div v-loading="listLoading" class="h-70%">
                                <div v-if="tableData.total > 0">
                                    <product-seach :list="tableData.list" :size-data="proSize" />
                                    <div class="acea-row row-middle mt-20px pb-10px">
                                        <el-pagination background layout="prev, pager, next" :total="tableData.total" class="page-item" :page-size="where.limit" :current-page="where.page" @update:current-page="pageChange" />
                                    </div>
                                </div>
                                <div v-else class="w-100%" :style="{ height: ScrollHeight + 'px' }">
                                    <empty-page title="暂无商品哟~">
                                        <template #emptyImage>
                                            <img src="@/assets/images/wushangpin.png" />
                                        </template>
                                    </empty-page>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped lang="scss">
.seckill_list {
  background-image: url('~/assets/images/miaoshabj.png');
  background-repeat: no-repeat;
  background-size: 100% 330px;
}
.wrapper_1200 {
  margin: 0 auto;
  width: 1200px;
}
.sologan {
  color: #777;
}
.hot {
  width: 224px;
  :deep .item {
    margin-right: 0;
  }
  .listStyle {
    background: #fff;
    padding: 12px 12px 12px 12px;
    width: 224px;
    border-radius: 6px;
    margin-top: 20px;
  }
}
.rightBox {
  width: 100%;
  margin-left: 20px;
  :deep .item:nth-child(4n) {
    margin-right: 0;
  }
  :deep .item:nth-child(5n) {
    margin-right: 15px;
  }
}
.title {
  color: #cc0000;
  font-size: 20px;
  margin-top: 20px;
}
</style>